<template>
<div class="login-box">
  <div class="login-card">
    <h2 class="title">欢迎登录</h2>
    <el-form
      :model="loginForm"
      :rules="rules"
      ref="formRef"
    >
      <el-form-item prop="userid" label="用户名">
        <el-input
          placeholder="请输入用户名"
          v-model="loginForm.userid"
          />
      </el-form-item>
      <el-form-item prop="password" label="密码">
        <el-input type="password"
                  placeholder="请输入密码"
                  v-model="loginForm.password"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm" class="submit-btn">
          登录
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</div>
</template>

<script setup>

import {reactive,ref} from "vue";
import axios from "axios";
import {ElMessage,ElForm} from "element-plus";
import { useRouter } from 'vue-router';

const router = useRouter(); // 获取路由实例

const loginForm=reactive({
  userid:'',
  password:''

})
const formRef=ref(null)


const rules ={
  userid: [
    {required: true, message: '请输入用户名', trigger:'blur' },
    {min: 3, max: 20, message: '长度在 3 到 20 字符', trigger: 'blur'}
  ],
  password: [
    {required: true, message: '请输入密码', trigger:'blur'},
    {min: 6, max: 20, message: '长度在 6 到 20 字符', trigger: 'blur'}
  ]
}

      const submitForm=async ()=>{

        if (!formRef.value) return
        try {
          await formRef.value.validate()
          axios.post("http://localhost:8080/users/login",loginForm).then(
              res=>{

                if (res.data.code == 200){
                    ElMessage.success('登录成功')
                    localStorage.setItem('token', res.data.token)//存储token
                    router.push('/SystemHome')
                }
                //
                else {
                  ElMessage.error('登录失败')
                }
              }
          )
        }catch (error){
        ElMessage.error('用户名或密码错误')
        }
      }
</script>
<style scoped>
.login-box {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background: #f5f7fa;
}

.login-card {
  width: 400px;
  padding: 30px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.title {
  text-align: center;
  margin-bottom: 24px;
  color: #303133;
}

.submit-btn {
  width: 100%;
  margin-top: 10px;
}
</style>